//
//  HMApplyFhotoTableViewCell.m
//  HMMarket
//
//  Created by haohao on 2017/6/26.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMApplyFhotoTableViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import "CTAssetsPickerController.h"
#import "HMSelectPhoto.h"

static ALAssetsLibrary *_library;

@interface HMApplyFhotoTableViewCell ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, CTAssetsPickerControllerDelegate, HMSelectPhotoDelegate>

NS_STRONG NSMutableArray *dataArray;
NS_STRONG NSMutableArray *imageArray;
NS_STRONG HMSelectPhoto  *selectPhoto;

@end


@implementation HMApplyFhotoTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    [_photoBtn addTarget:self action:@selector(takePhoto) forControlEvents:UIControlEventTouchUpInside];
    self.backgroundColor = [UIColor colorWithRed:238/255.0 green:238/255.0 blue:238/255.0 alpha:1.0];
    _warnLabel.textColor = kc9c9c9;
    // Initialization code
}

- (void)takePhoto {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"1");
        if (self.dataArray.count + self.imageArray.count > 3) {
            [HMHUDManager showHUDWithText:@"最多三张"];
        } else {
            // 相机权限
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
            if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。
                
                authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
            {
                // 无权限 引导去开启
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请前往设置->隐私->授权应用使用相册权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    // 一键到达app独立的隐私配置页
                    NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] canOpenURL:url];
                    }
                }];
                [alertController addAction:alertAction];
                [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
                
            }else{
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
                    imagePickerController.NavigationBarHideEnabled = NO;
                    //判断是否支持摄像机
                    BOOL isCameraSupport = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
                    NSLog(@"SUPPORT CAMERA:%d", isCameraSupport);
                    BOOL isRearSupport = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
                    NSLog(@"rear support:%d", isRearSupport);
                    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                    imagePickerController.showsCameraControls = YES;
                    imagePickerController.delegate = self;
                    [[self getCurrentVC] presentViewController:imagePickerController animated:YES completion:nil];
                }
                else
                {
                    NSLog(@"手机不支持相机");
                }
            }
        }
    }];
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied) {
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"请前往设置->隐私->授权应用使用相册权限" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                // 一键到达app独立的隐私配置页
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] canOpenURL:url];
                }
            }];
            [alertController addAction:alertAction];
            [[self getCurrentVC] presentViewController:alertController animated:YES completion:nil];
        } else {
            if (self.dataArray.count + self.imageArray.count >= 3) {
                [HMHUDManager showHUDWithText:@"最多三张"];
            } else {
                CTAssetsPickerController *imagePic = [[CTAssetsPickerController alloc]init];
                imagePic.assetsFilter         = [ALAssetsFilter allPhotos];
                imagePic.showsCancelButton    = YES;
                imagePic.delegate             = self;
                imagePic.selectedAssets       = self.dataArray;
                [[self getCurrentVC] presentViewController:imagePic animated:YES completion:nil];
            }
         
        }
    }];
    UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [[self getCurrentVC] presentViewController:alert animated:YES completion:nil];

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}


#pragma mark - UIPickerViewDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    if (self.dataArray.count + self.imageArray.count > 3) {
        [HMHUDManager showHUDWithText:@"最多三张"];
    } else {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.imageArray addObject:image];
        [picker dismissViewControllerAnimated:YES completion:nil];
        if (self.imageArray.count > 0) {
            self.warnLabel.hidden = YES;
            self.selectPhoto.hidden = NO;
            self.selectPhoto.imageArray = _imageArray;
        } else {
            self.warnLabel.hidden = NO;
            self.selectPhoto.hidden = YES;
        }
        if ([_delegate respondsToSelector:@selector(selectPhoto:image:)]) {
            [_delegate selectPhoto:_dataArray image:_imageArray];
        }
    }
}

//- (void)saveImageToPhotos:(UIImage*)savedImage
//{
//    _library = [[ALAssetsLibrary alloc] init];
//    __weak __typeof__(self) weakSelf = self;
//    [_library writeImageToSavedPhotosAlbum:[savedImage CGImage] orientation:(ALAssetOrientation)[savedImage imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
//            [_library assetForURL:assetURL resultBlock:^(ALAsset *asset){//这里的asset便是我们所需要的图像对应的ALAsset了
//                ALAsset *ass = [asset copy];
//                [weakSelf.dataArray addObject:ass];
//            }failureBlock:^(NSError *error) {
//                //                [[YYViewControllerCenter currentVisiableRootViewController] dismissViewControllerAnimated:NO completion:^{}];
//            }];
//        });
//    }];
//}

#pragma mark - CTAssetsPickerControllerDelegate
- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    
    if (self.dataArray.count + self.imageArray.count > 3) {
        [HMHUDManager showHUDWithText:@"最多三张"];
    } else {
        if (self.imageArray.count + self.dataArray.count > 0) {
            _warnLabel.hidden = YES;
            self.selectPhoto.hidden = NO;
            self.selectPhoto.imageArray = _imageArray;
            self.selectPhoto.dataArray = _dataArray;
        } else {
            self.warnLabel.hidden = NO;
            self.selectPhoto.hidden = YES;
        }
        if ([_delegate respondsToSelector:@selector(selectPhoto:image:)]) {
            [_delegate selectPhoto:_dataArray image:_imageArray];
        }
        [picker dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - HMSelectPhotoDelegate
- (void)returnImageArray:(NSMutableArray *)imageArray with:(senderType)senderType{
    if (senderType == DATA_ARRAY) {
        _dataArray = imageArray;
    } else {
        _imageArray = imageArray;
    }
    
    if (self.imageArray.count + self.dataArray.count > 0) {
        _warnLabel.hidden = YES;
        self.selectPhoto.hidden = NO;
    } else {
        self.warnLabel.hidden = NO;
        self.selectPhoto.hidden = YES;
    }
    if ([_delegate respondsToSelector:@selector(selectPhoto:image:)]) {
        [_delegate selectPhoto:_dataArray image:_imageArray];
    }
}


- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    return result;
}

- (HMSelectPhoto *)selectPhoto {
    if (_selectPhoto == nil) {
        _selectPhoto = [[HMSelectPhoto alloc] init];
        _selectPhoto.delegate = self;
        [self addSubview:_selectPhoto];
    }
    return _selectPhoto;
}

- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

@end
